package com.example.myspring.service;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;

@Service
public class CaptchaService {

    private static final int WIDTH = 100;
    private static final int HEIGHT = 30;
    private static final Font RANDOM_FONT = new Font("Fixedsys", Font.PLAIN, 18);
    private static final int CODE_LENGTH = 4; // 验证码长度
    private static final String CODE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    public byte[] generateCaptchaImage(HttpSession session) {
        String captchaText = generateCaptchaText();
        session.setAttribute("captcha", captchaText); // 将验证码保存到session中

        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);
        g.setFont(RANDOM_FONT);
        g.setColor(getRandomColor());
        g.drawString(captchaText, 10, 20);
        g.dispose();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpeg", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray(); // 返回验证码图片的字节数组
    }

    private String generateCaptchaText() {
        StringBuilder captcha = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < CODE_LENGTH; i++) {
            int index = random.nextInt(CODE_CHARACTERS.length());
            captcha.append(CODE_CHARACTERS.charAt(index));
        }
        return captcha.toString();
    }

    private Color getRandomColor() {
        Random random = new Random();
        int red = random.nextInt(255);
        int green = random.nextInt(255);
        int blue = random.nextInt(255);
        return new Color(red, green, blue);
    }
}